
#导入蓝图，个人中心模块
from flask import g, render_template
from flask import redirect, jsonify
from flask import request, current_app, session

from info.utils.response_code import RET
from . import profile_blu
from info import db

#导入登录验证装饰器
from info.utils.commons import login_required




@profile_blu.route('/info')
@login_required
def user_info():
    """
    1、尝试获取用户登录信息并判断
    2、默认加载模板页面

    :return:
    """
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user':user.to_dict()
    }

    return render_template('news/user.html', data=data)


@profile_blu.route('/base_info', methods=['GET', 'POST'])
@login_required
def base_info():
    """
    个人信息修改
    1、如果是post请求， 获取参数
    2、校验参数完整性
    3、判断用户性别
    4、保存用户修改的信息
    5、提交数据
    6、返回结果
    :return:
    """

    user = g.user

    if not user:
        return jsonify(errrno=RET.DBERR, errmsg='用户未登录1')

    if request.method == 'GET':
        data = {
            'user':user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)

    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')

    if not all([nick_name, signature, gender]):
        return jsonify(errrno=RET.DBERR, errmsg='参数不完整1')

    if gender not in ['MAN', 'WOMEN']:
        return jsonify(errrno=RET.DBERR, errmsg='性别范围不正确')

    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errrno=RET.DBERR, errmsg='提交数据失败')
    #缓存用户昵称
    session['nick_name'] = user.nick_name
    return jsonify(errrno=RET.OK, errmsg='OK')





